import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from Model.models import Client, Contract, Package
from tools.Tools import getFileBytes, getCurrentUser
from tools.createBusiness import createAuthInfo, createIncomeTotal, createIncomeDetail

logger_info = logging.getLogger('info')
res = dict()


def importClientAndContract(request):
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            upload_data = body.get('list')
            operator = getCurrentUser(request)
            """{'联系人': '张三', '手机号': '13918026169', '套餐': '100M', '开始时间': '2021-12-03', '结束时间': '2024-04-20', 
            '装维人员': '装维人员1', '详细地址': '浑南新区', '宽带账号': 'sy00000001', '宽带密码': 'h85ypw', 
            '身份证': '210102199003075971', '光猫码': ''}"""
            for data in upload_data:
                name, telephone, package, start, end, installer, address, \
                account_number, account_password, certificate, code, memo = data.values()
                if '1、' not in name and '2、' not in name and '3、' not in name and \
                        '4、' not in name and name != '' and name != '说明':
                    packageId = getPackageId(package)
                    if not packageId:
                        packageId = Package.objects.first().package_id
                    clientData = createClient(name, telephone, address, certificate, str(operator))
                    if code == "":
                        code = None
                    createContract(clientData, packageId, start, end, installer, account_number, account_password,
                                   str(operator), memo, code)
            res['status'] = 200
            res['message'] = '导入成功!'
            return JsonResponse(res, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


def getPackageId(package):
    try:
        packageId = Package.objects.get(package_name=package).package_id
    except:
        logger_info.error(f'当前方法：getPackageId 异常，异常内容为:{traceback.format_exc()}')
        packageId = None
    return packageId


@transaction.atomic
def createClient(name: str, telephone: str, address: str, certificate: str, operator: str):
    """
    :param name 客户名
    :param telephone 电话
    :param address 详情地址
    :param certificate 证件号码
    :param operator 当前操作人
    """
    if not Client.objects.filter(name__contains=name, telephone__contains=telephone).exists():
        createDate = Client.objects.create()
        createDate.client_id = createDate.id
        createDate.name = name
        createDate.telephone = telephone
        createDate.install_address = address
        createDate.certificate_type = 1
        createDate.certificate = certificate
        createDate.operator = operator
        createDate.create_date = datetime.now()
        createDate.save()
        return createDate
    else:
        oldData = Client.objects.get(name__contains=name, telephone__contains=telephone)
        return oldData


@transaction.atomic
def createContract(client: Client, packageId: int, start: str, end: str, installer: str, account_number: str,
                   account_password: str, operator: str, memo: str, code=None):
    """
    :param client 客户数据
    :param packageId 套餐ID
    :param start 开始时间
    :param end 到期时间
    :param installer 装维
    :param account_number 账号
    :param account_password 密码
    :param operator 操作人
    :param memo 备注
    :param code 光猫码
    """
    try:
        timeNow = str(datetime.now())[:10]
        createDate = Contract.objects.create()
        createDate.contract_id = createDate.id
        createDate.client_id = client.client_id
        createDate.linkman = client.name
        createDate.link_telephone = client.telephone
        createDate.service_package = packageId
        createDate.start_date = start
        createDate.end_date = end
        createDate.state = 1 if end > timeNow else 0
        createDate.renew_state = 0
        createDate.installer = installer
        createDate.install_address = client.install_address
        createDate.create_date = datetime.now()
        createDate.account_number = account_number
        createDate.account_password = account_password
        createDate.operator = operator
        createDate.memo = '%s 日导入数据，原备注：%s' % (timeNow, memo)
        createDate.save()
        if code:
            totalId = createIncomeTotal(createDate.contract_id, client.client_id, 1, operator, createDate.memo)
            createIncomeDetail(totalId, createDate.contract_id, 4, 0, equipmentType='光猫', code=code,
                               memo=createDate.memo)
        createAuthInfo(account_number, account_password, packageId, end)

    except:
        logger_info.error(f'当前方法：createContract 异常，异常内容为:{traceback.format_exc()}')


def downloadResource(request):
    res.clear()
    try:
        if request.method == 'GET':
            out_stream = getFileBytes('zy.xls')
            response = HttpResponse(content_type='application/vnd.ms-excel', charset="UTF-8")
            response.write(out_stream)
            return response
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
